package com.cwits.wifi.ui.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cwits.wifi.R;
import com.cwits.wifi.base.BaseActivity;
import com.cwits.wifi.manager.ControlManager;
import com.cwits.wifi.ui.dialog.TwoDialog;
import com.cwits.wifi.util.Dbug;
import com.cwits.wifi.util.IAction;
import com.jieli.lib.stream.beans.StateInfo;
import com.jieli.lib.stream.beans.VideoInfo;
import com.jieli.lib.stream.tools.ParseHelper;

import java.util.List;

/**
 * 存储管理
 * Created by Admini2016/2/26.
 */
public class StorageMgrActivity extends BaseActivity implements View.OnClickListener {

    private boolean unLock = false;
    private int mProgress;
    private RelativeLayout mBack, mRlWaring;
    private Button mBtn;
    private ProgressBar mPbSOS;
    private TextView mTvProgress, mTvNeedDel, mTvClean;
    private ProgressDialog pd;
    private TwoDialog twoDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.stoarge_infolayout);
        mBack = (RelativeLayout) findViewById(R.id.left_imageview);
        mRlWaring = (RelativeLayout) findViewById(R.id.stoarge_rl_warring);
        mTvClean = (TextView) findViewById(R.id.storage_tv_clean);
        mTvNeedDel = (TextView) findViewById(R.id.storage_tv_3);
        mBtn = (Button) findViewById(R.id.storage_btn);
        mPbSOS = (ProgressBar) findViewById(R.id.sosprogressbar);
        mTvProgress = (TextView) findViewById(R.id.progress_textview);
        mTvProgress.setText(getString(R.string.stor_user)+" 0%");
        mBtn.setOnClickListener(this);
        mBack.setOnClickListener(this);
        registerGetSOSStorageInfo();
        if (mApplication.getIsOffLineMode() == false) {
            //已经连接设备wifi
            showProcessDialog();
            ControlManager.getInstance().sendCommand("2", "0553", "0");
            mRlWaring.setVisibility(View.GONE);
        } else {
            //没有连接设备wifi
            mRlWaring.setVisibility(View.VISIBLE);
            //showToast("对不起，没有连接168设备WiFi！");
        }
    }

    @Override
    public void onWiFiState(boolean isAutoDisable, int state) {
        super.onWiFiState(isAutoDisable, state);
        switch (state) {
            case 1:
                break;
            case 2:
                connectError();
                break;
        }
    }


    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_GET_SOSSTORAGE_INFO)) {
                final StateInfo stateInfo = (StateInfo) intent.getSerializableExtra(KEY_GETSOSSTORAGE_INFO);
                hideProgressDialog();
                String progessstr = stateInfo.getParam()[0];
                int index = progessstr.lastIndexOf(",");
                String pr = progessstr.substring(index + 1, progessstr.length());
                mProgress = Integer.valueOf(pr);
                if (mProgress == -1)
                    mProgress = 0;
                if (pd != null){
                    handler1.sendEmptyMessageDelayed(1111, 5000);
                }else{
                    if (mProgress != 0) {  //解锁失败
                        mPbSOS.setProgress(mProgress);
                        mTvNeedDel.setVisibility(View.GONE);
                        mTvProgress.setText(getString(R.string.stor_user)+" " +String.valueOf(mProgress) + "%");
                        mBtn.setText(getString(R.string.stor_nulock));
                        mTvClean.setText(getString(R.string.stor_is_lock));
                    } else {   //解锁成功
                        unLock = true;
                        mTvNeedDel.setVisibility(View.VISIBLE);
                        mTvProgress.setText(getString(R.string.stor_user)+" " +String.valueOf(mProgress) + "%");
                        //mBtn.setText(getString(R.string.stor_wancheng));
                        mBtn.setBackgroundResource(R.drawable.stoarge_bg_gary);
                        mTvClean.setText(getString(R.string.stor_no_clean));
                    }
                }

            } else if (ACTION_RELEASE_SOSSTORAGE_INFO.equals(action)) {
                final StateInfo stateInfo = (StateInfo) intent.getSerializableExtra(KEY_RELEASESOSSTORAGE_INFO);
                String state = stateInfo.getParam()[0];
                if (state.equals("0")) {
                    //error
                    showToastLong(getString(R.string.stor_lock_err));
                    if (pd != null)
                        handler1.sendEmptyMessageDelayed(1112, 5000);
                } else if (state.equals("1")) {
                    showToastLong(getString(R.string.stor_lock_sucess));
                    ControlManager.getInstance().sendCommand("2", "0553", "0");
                    ControlManager.getInstance().requestStatus(CTP_ID_DEFAULT, CMD_ALL_VIDEO_DESC_NAME);
                }
            } else if (ACTION_GET_ALL_VIDEO_FILE_NAME.equals(action)) {
                final StateInfo stateInfo = (StateInfo) intent.getSerializableExtra(KEY_GET_ALL_VIDEO_FILE_NAME);
                String state = stateInfo.getParam()[0];
                if (ARGS_ALL_VIDEO_DESC_NAME_SUCCESS.equals(state)) {
                    final String videoListFileName = stateInfo.getParam()[1];

                    ParseHelper.getInstance().requestVideoInfoText(mApplication.getApplicationContext(), videoListFileName, new ParseHelper.ResponseListener() {
                        @Override
                        public void onResponse(boolean isSuccess) {
                            if (isSuccess) {
                                List<VideoInfo> vf = ParseHelper.getInstance().getSortedVideos();
                            } else {
                                Dbug.w("-------", "Request " + videoListFileName + " fail!");
                            }
                        }
                    });
                }
            }
        }
    };

    private void registerGetSOSStorageInfo() {
        IntentFilter intentFilter = new IntentFilter(IAction.ACTION_GET_SOSSTORAGE_INFO);
        intentFilter.addAction(IAction.ACTION_RELEASE_SOSSTORAGE_INFO);
        intentFilter.addAction(ACTION_GET_ALL_VIDEO_FILE_NAME);
        this.registerReceiver(mReceiver, intentFilter);
    }

    private void unRegisterGetSOSStorageInfo() {
        this.unregisterReceiver(mReceiver);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.left_imageview:
                finish();
                break;
            case R.id.storage_btn:
                if (mApplication.getIsOffLineMode() == false) {
                    //连接
                    if (0 != mProgress) {
                        //删除SOS视频
                        // showTwoDialog();
                        showUnLock();
                    } else {
                        //finish();
                        //showToastLong("不需要解锁");
                    }
                } else {
                    //未连接
                    showToastLong(getString(R.string.please_connect));
                }

                break;

        }
    }

    private void showUnLock() {
        twoDialog = new TwoDialog(StorageMgrActivity.this, getString(R.string.dialog_tip), getString(R.string.stor_is_clean_all), unlockListener);
        twoDialog.show();
    }

    private View.OnClickListener unlockListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.dialog_btn2_rl_ok:

                    twoDialog.dismiss();
                    ControlManager.getInstance().sendCommand("2", "0554", "");
                    pd = ProgressDialog.show(StorageMgrActivity.this, getString(R.string.stor_nulock), getString(R.string.stor_cleaning));

                    break;
                case R.id.dialog_btn2_rl_canale:
                    twoDialog.dismiss();
                    break;
            }
        }
    };

    private void showTwoDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(StorageMgrActivity.this);
        // final Dialog builder = new Dialog(getApplicationContext());
        View view = View.inflate(StorageMgrActivity.this, R.layout.dialog_btn2,
                null);
        TextView tvInfo = (TextView) view.findViewById(R.id.dialog_btn2_tv_info);
        RelativeLayout rlClose = (RelativeLayout) view.findViewById(R.id.dialog_btn2_rl_canale);
        RelativeLayout rlOk = (RelativeLayout) view.findViewById(R.id.dialog_btn2_rl_ok);
        tvInfo.setText(getString(R.string.stor_is_clean_all));
        builder.setView(view);

        final AlertDialog dialog = builder.create();

        rlOk.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                dialog.dismiss();
                ControlManager.getInstance().sendCommand("2", "0554", "");
                pd = ProgressDialog.show(StorageMgrActivity.this, getString(R.string.stor_nulock), getString(R.string.stor_cleaning));

            }
        });

        rlClose.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setView(view, 0, 0, 0, 0);
        dialog.show();
        builder.setCancelable(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegisterGetSOSStorageInfo();
    }

    @Override
    public void finish() {
        if (unLock) {
            MainActivity.CLEAN_SOS = true;
        }
        super.finish();
    }

    private Handler handler1 = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1111://成功
                    mPbSOS.setProgress(mProgress);
                    unLock = true;
                    mTvNeedDel.setVisibility(View.VISIBLE);
                    mTvProgress.setText(getString(R.string.stor_user)+" " +String.valueOf(mProgress) + "%");
                    //mBtn.setText(getString(R.string.stor_wancheng));
                    if(mProgress == 0){
                        mBtn.setBackgroundResource(R.drawable.stoarge_bg_gary);
                        mTvClean.setText(getString(R.string.stor_not_clean));
                    }else{
                        mTvClean.setText(getString(R.string.stor_is_clean_all));
                    }

                    pd.dismiss();
                    break;
                case 1112://失败
                    pd.dismiss();
                    mTvNeedDel.setVisibility(View.GONE);
                    mTvProgress.setText(getString(R.string.stor_user)+" " +String.valueOf(mProgress) + "%");
                    mBtn.setText(getString(R.string.stor_nulock));
                    mTvClean.setText(getString(R.string.stor_is_clean_all));
                    break;
            }
        }
    };
}
